#import <Cocoa/Cocoa.h>
#include <AppKit/AppKit.h>
#include <Foundation/NSObject.h>
#include "MacWindow.h"
#include "ExtException.h"
#include "eerrors.h"

MacWindow::MacWindow(const WindowSetup& setup)
	: m_setup(setup) {

    // Init application instance
    [NSAutoreleasePool new];
    [NSApplication sharedApplication];
    [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
    id menubar = [[NSMenu new] autorelease];
    id appMenuItem = [[NSMenuItem new] autorelease];
    [menubar addItem:appMenuItem];
    [NSApp setMainMenu:menubar];
    id appMenu = [[NSMenu new] autorelease];
    id appName = [[NSProcessInfo processInfo] processName];
    id quitTitle = [@"Quit " stringByAppendingString:appName];
    id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:quitTitle action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
    [appMenu addItem:quitMenuItem];
    [appMenuItem setSubmenu:appMenu];
        
    // Create window
    NSRect frame = NSMakeRect(0, 0, m_setup.Width, m_setup.Height);
    m_window = [[NSWindow alloc] initWithContentRect:frame styleMask:NSMiniaturizableWindowMask | NSTitledWindowMask | NSClosableWindowMask backing:NSBackingStoreBuffered defer:NO];
    if(!m_window) {
        //NSLog(@"Failed to allocated the window.");
        throw runtime_error(ENGINE_WINDOW_ERROR_CREATE);
        //[NSApp terminate:nil];
    }
    [m_window setTitle:@"OGLES Player"];
    // Create our view
    m_view = [[NSView alloc] initWithFrame:frame];
    // Now we have a view, add it to our window
    [m_window setContentView:m_view];
    [m_window makeKeyAndOrderFront:nil];
    // Add an observer so when our window is closed we terminate the app
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(terminateApp) name:NSWindowWillCloseNotification object:m_window];
    // Run the application
    [NSApp activateIgnoringOtherApps:YES];
}

MacWindow::~MacWindow() {
    if (m_window) {
        [m_window release];
        m_window = nil;
    }
    if (m_view) {
        [m_view release];
        m_view = nil;
    }
}

WND_STATUS MacWindow::ProcessMessage() const {
    [NSApp run];
	return WND_OK;
}

inline uint32_t MacWindow::GetWidth() const {
	return m_setup.Width;
}

inline uint32_t MacWindow::GetHeight() const {
	return m_setup.Height;
}

inline WND_HANDLE MacWindow::GetWindowHandle() const {
	return m_window;
}

IEngineWindowPtr CreateEngineWindow(const WindowSetup& setup)
{
    return make_shared<MacWindow>(setup);
}